package game.net.server;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.util.List;

public class ServerListener implements Runnable{
	Server server;
	ServerSocket ss;
	boolean listening;
	int listeningPort;
	private ErrorLog errorLog;
	
	public ServerListener(Server server, int port){
		this(server, port, null);
	}
	
	public ServerListener(Server server, int port, ErrorLog errorLog) {
		this.server = server;
		this.errorLog = errorLog;
		try {
			ss = negotiatePort(port);
		} catch (Exception e) {
			this.errorLog.reportError(e);
		}		
	}	

	private ServerSocket negotiatePort(int port) throws IOException {
		ServerSocket output = null;
		listeningPort = port;
		
		try {
			output = new ServerSocket(port);
		} catch (BindException e){
			negotiatePort(port+1);
		}
		
		return output;
	}
	
	public void listen(){
		try {
			server.createNewConnection(ss.accept());
		} catch (Exception e) {
			errorLog.reportError(e);
		}	
	}

	@Override
	public void run() {
		listening = true;
		while(listening)
			listen();
	}

}
